package com.itshops.service.impl;

import com.itshops.dao.CartDao;
import com.itshops.dao.OrderDao;
import com.itshops.dao.impl.CartDapImpl;
import com.itshops.dao.impl.OrderDaoImpl;
import com.itshops.entity.Cart;
import com.itshops.entity.Item;
import com.itshops.entity.Orders;
import com.itshops.service.OrderService;
import com.itshops.utils.RandomUtils;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class OrderServiceImpl implements OrderService {
    OrderDao orderDao=new OrderDaoImpl();
    @Override
    public void crateOrder(String aid, String uid, String sum) throws SQLException, InvocationTargetException, IllegalAccessException {
        //创建订单对象保存数据
        Orders orders = new Orders();
        String orderId = RandomUtils.createOrderId();
        orders.setOid(orderId);
        orders.setUid(Integer.parseInt(uid));
        orders.setAid(Integer.parseInt(aid));
        orders.setOtime(new Date());
        orders.setOcount(new BigDecimal(sum));
        orders.setOstate(1);
        //保存订单
        orderDao.insertOrder(orders);
        //将购物车转成订单项
        CartDao cartDao=new CartDapImpl();
        List<Cart> carts = cartDao.selectCartsByUid(Integer.parseInt(uid));
        List items=new ArrayList();
        for (Cart cart : carts) {
            Item item = new Item();
            item.setOid(orderId);
            item.setPid(cart.getPid());
            item.setProduct(cart.getProduct());
            item.setIcount(cart.getCcount());
            item.setInum(cart.getCnum());
            items.add(item);
        }
        //保存订单对应的订单项
        orderDao.insertItems(items);
        //清空购物车
        cartDao.deleteCarByUid(uid);
    }

    @Override
    public List<Orders> fianAll(int uid) throws SQLException, InvocationTargetException, IllegalAccessException {
        List<Orders> orders=orderDao.selectByUid(uid);
        return orders;
    }

    @Override
    public Orders findOrderByoid(String oid) throws SQLException, InvocationTargetException, IllegalAccessException {
        //用Uuid查询订单和和地址
        Orders order=orderDao.selectOrderByOid(oid);
        //用uid查询订单项和商品信息
        List<Item> item=orderDao.selectItemByOid(oid);

        order.setItems(item);
        return order;
    }

    @Override
    public void updateOrderByOid(String oid) throws SQLException {
        //支付后修改订单支付状态
        orderDao.updateStateByOid(oid);
    }

}
